<?php

namespace App\Http\Middleware;

use Closure;
use App\Models\FormId;

class RecordFormId
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        return $next($request);
    }

    public function terminate($request, $response)
    {
        $formId = $request->headers->get('x-form-id');
        if (empty($formId)) {
            return;
        }
        $user = $request->user();
        $thirdPartyBind = $user->thirdPartyBinds()->platformWeixinOpen()->firstOrFail();
        foreach (explode(',', $formId) as $value) {
            $item = explode('_', $value);
            if ($item[1] <= time() || strpos($item[0], 'mock one')) {
                continue;
            }
            FormId::create([
                'uid' => $user->id,
                'openid' => $thirdPartyBind->openid,
                'form_id' => $item[0]
            ]);
        }

    }
}
